package com.jml.EsWangPan.controller;

import com.google.common.collect.Lists;
import com.jml.EsWangPan.entity.CloudDiskEntity;
import com.jml.EsWangPan.dao.CloudDiskDao;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// SpringBoot 整合ES增删改查
@RestController
public class CloudDiskController {

	@Autowired
	private CloudDiskDao cloudDiskDao;

	//根据id查询
	@RequestMapping("/findById/{id}")
	public Optional<CloudDiskEntity> findById(@PathVariable String id) {
		return cloudDiskDao.findById(id);
	}

	//查询所有的
	@RequestMapping("/mysearchAll")
	public List<CloudDiskEntity> mysearchAll() {
		// 查询所有的
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		Iterable<CloudDiskEntity> search = cloudDiskDao.search(boolQuery);
		return Lists.newArrayList(search);
	}

	//两个字段联合在一起的的模糊查询
	@RequestMapping("/searchanddescribe")
	public List<CloudDiskEntity> searchanddescribe(String keyWord,String describe) {
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		//条件查询，对name字段进行迷糊查询
		if (!StringUtils.isEmpty(keyWord)) {
			// 模糊查询 一定要ik中文
			MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyWord);
			boolQuery.must(matchQuery);
		}
		//条件查询，对describe字段进行迷糊查询
		if (!StringUtils.isEmpty(describe)) {
			// 精确查询查询 一定要ik中文
			MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("describe", describe);
			boolQuery.must(matchQuery);
		}
		Iterable<CloudDiskEntity> search = cloudDiskDao.search(boolQuery);
		return Lists.newArrayList(search);

	}

	//page，value可以当做参数传递过来，如果没有及时自己设定的，如果有参数，就用传过来的参数值
	//?page=1&&value=3
	// page 表示请求的页数从0开始
	// value size 每一页展示多少条数据
	// @PageableDefault 默认值
	// keyWord=2018史上最全SpringBoot 拆分成 史上，最全，springboot
	@RequestMapping("/searchPage")
	public Page<CloudDiskEntity> search(String keyWord, @PageableDefault(page = 0, value = 2) Pageable pageable) {
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		//条件查询，对name字段进行迷糊查询
		if (!StringUtils.isEmpty(keyWord)) {
			// 模糊查询 一定要ik中文
			MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyWord);
			boolQuery.must(matchQuery);
		}
		Page<CloudDiskEntity> page = cloudDiskDao.search(boolQuery, pageable);
		return page;

	}



}
